from ninja import Router, Schema, Query
from django.db import connection
from django.core.paginator import Paginator
from utils.cj_response import ErrorResponse
from utils.sql_fet_list import dictfetchall
from utils.cj_auth import check_token

router = Router()


class PagesSchema(Schema):
    page: int = 1
    limit: int = 10


@router.get("order/list/tree")
def order_list(request, pages: PagesSchema = Query(...)):
    """
    获取所有订单
    :param request:
    :param pages:
    :return:
    """
    if not pages.page or not pages.limit:
        return ErrorResponse(msg="分页参数不能为空")
    with connection.cursor() as cur:
        cur.execute('select * from `order`')
        result = dictfetchall(cur)
    paginator = Paginator(result, pages.limit)
    page_1 = paginator.get_page(pages.page)
    data_liat = []
    for i in page_1:
        i['goods_info'] = eval(i['goods_info'])
        data_liat.append(i)
    data = {
        "data_liat": data_liat,
        "total": paginator.count
    }
    return data


@router.put("/orders/status")
@check_token
def update_order(request):
    """
    修改订单信息
    :param request:
    :return:
    """
    with connection.cursor() as cur:
        cur.execute(f'update `order` set status={request.GET.get("status")} where key_id={request.GET.get("key_id")}')
        cur.fetchall()
    return "修改成功"

